﻿using System.Text;

namespace Infrastructure.Utils
{
    public class ConvertHelper
    {
        #region 字节数组byte[] <=> 16进制字符串
        /// <summary>
        /// byte[]转为16进制字符串
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static string ByteToHexString(byte[] b)
        {
            //同 BitConverter.ToString(b).Replace("-", "").ToLower()
            var sb = new StringBuilder();
            for (int i = 0; i < b.Length; i++)
            {
                sb.Append(b[i].ToString("x2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 将16进制的字符串转为byte[]
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        public static byte[] HexStringToByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        #endregion

        #region base64字符串 <=> 普通字符串
        /// <summary>
        /// base64字符串 > 字符串
        /// MQ==：1
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>

        public static string Base64ToString(string source)
        {
            return Encoding.Default.GetString(Convert.FromBase64String(source));
        }
        /// <summary>
        /// 字符串 > base64字符串
        /// 1: MQ==
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string StringToBase64(string source)
        {
            return Convert.ToBase64String(Encoding.Default.GetBytes(source));
        }
        #endregion
    }
}
